import Vue from 'vue'

/**
 * 防抖：多次执行，只执行一次，再次触发，会重新计算时间，例如搜索
 * @param {Number} delay  延时时间
 * @param {Function} fn  回调函数
 * @example v-debounce="{fn: func, delay: 1000}"
 */
Vue.directive('debounce', {
  bind: function (el, binding, vnode) {
    let { delay, fn } = binding.value
    delay = delay ? delay : 500
    let timer = null
    let inx = 0
    el.addEventListener('input', () => {
      if (timer) {
        clearTimeout(timer)
      }
      timer = setTimeout(() => {
        fn.apply(this, arguments)
        timer = null
      }, delay)
    })
  }
})

/**
 * 节流：单位时间内只执行一次，例如监听滚动事件，抢票，
 * @param {Number} delay  延时时间
 * @param {Function} fn  回调函数
 * @example v-throttle="{fn: func, delay: 1000}"
 */
Vue.directive('throttle', {
  bind: function (el, binding, vnode) {
    let { delay, fn } = binding.value
    delay = delay ? delay : 500
    let timer = null
    el.addEventListener('click', () => {
      if (!timer) {
        timer = setTimeout(() => {
          fn.apply(this, arguments)
          timer = null
        }, delay)
      }
    })
  }
})